package demo5;

import java.util.Stack;

public class MinStack {
    public Stack<Integer> stack;
    public Stack<Integer> minstack;
    public MinStack(){
        stack=new Stack<>();
        minstack=new Stack<>();
    }
    public void push(int val){
        stack.push(val);
        if(minstack.isEmpty()){
            minstack.push(val);
        }else{
            if(val<=minstack.peek()){   //获取最小栈顶元素，若大于输入值，则将输入值在存入主栈后再存入最小栈
                minstack.push(val);
            }
        }
    }
    public void pop(){      //主栈完成弹出一个元素的操作，辅助最小值栈保证栈顶仍然是主栈剩余元素的最小值，其栈顶若与主栈栈顶相同则弹出保持
        if(minstack.isEmpty()){
            return;
        }
        int val=stack.pop();
        if(val== minstack.peek()){
            minstack.pop();
        }

    }
    public int top(){       //获取主栈栈顶元素
        if(stack.isEmpty()){
            return -1;
        }
        return stack.peek();
    }
    public int getmin(){
        if(minstack.isEmpty()){
            System.out.println("没找到！！！");
            return -1;
        }
        return minstack.peek();
    }
}
